<template>
    <div class="container-fluid" v-loading="loading">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        {{ companyName }}
                        &nbsp;&nbsp;
                        <el-button size="mini" type="danger" v-if="status===1" @click="handleSetStatus(companyId,0)">
                            停用
                        </el-button>
                        <el-button size="mini" type="success" v-if="!status" @click="handleSetStatus(companyId,1)">开启
                        </el-button>
                    </div>
                    <div class="card-toolbar clearfix">
                        <form class="form-inline" onsubmit="return false;">
                            <div class="form-group">
                                <label>公司别名</label>
                                <el-tag
                                        :key="tag"
                                        v-for="tag in alternativeName"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(tag)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="inputVisible"
                                        v-model="inputValue"
                                        ref="saveTagInput"
                                        @keyup.enter.native="handleInputConfirm"
                                        @blur="handleInputConfirm"
                                        style="width: 40%;"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加公司别称
                                </el-button>
                            </div>

                            <!--<div class="form-group">
                                <label>所属分类</label>
                                <el-autocomplete
                                        v-model="categoryName"
                                        :fetch-suggestions="querySearchAsync"
                                        placeholder="请输入内容"
                                        @select="handleSelect"
                                ></el-autocomplete>
                                <el-tag
                                        :key="tag.id"
                                        v-for="tag in categoryTags"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleIndustryClose(tag)">
                                    {{tag.value}}
                                </el-tag>
                            </div>-->

                        </form>
                    </div>

                    <company-menu-components :company-id="companyId" :active-index="activeIndex"></company-menu-components>


                    <div class="card-body">
                        <div>
                            <form class="form-inline" onsubmit="return false;">
                                <div class="form-group">
                                    <input class="form-control" type="text" id="example-if-email"
                                           name="example-if-email" placeholder="请输入抖音|快手链接" v-model="url" autocomplete="off">
                                </div>
                                <div class="form-group">
                                    <button class="btn btn-success" type="button" v-on:click="draw()">提取视频</button>
                                </div>
                                <div class="form-group" style="margin-right:40px;">
                                    <a href="/admin/video/create">
                                        <button class="btn btn-success" type="button">直接创建</button>
                                    </a>
                                </div>
                                <div class="form-group">
                                    <label class="sr-only" for="example-if-password">请视频标题</label>
                                    <input class="form-control" type="text" id="example-if-password"
                                           name="example-if-password" placeholder="请请视频标题" v-model="keyword" autocomplete="off">
                                </div>
                                <div class="form-group">
                                    <el-select v-model="search_status" placeholder="全部">
                                        <el-option
                                                v-for="item in options"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="form-group">
                                    <button class="btn btn-success" type="submit" v-on:click="search()">筛选</button>
                                </div>
                            </form>
                        </div>
                        <div class="table-responsive" style="width: 100%;margin-top: 20px;">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    @sort-change='sortChange'
                                    :default-sort="{prop: 'date', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        align="center"
                                        :index="indexMethod"
                                        width="50">
                                </el-table-column>
                                <el-table-column
                                        prop="title"
                                        label="视频标题"
                                        align="center"
                                        width="140">
                                    <template slot-scope="scope">
                                        <a :href="'/admin/video/'+scope.row._id+'/edit'" target="_blank" style="cursor:pointer;">{{scope.row.title |
                                            titleFormatter}}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="companyStr"
                                        label="所属公司"
                                        align="center"
                                        :formatter="formatCompany"
                                        width="100">
                                </el-table-column>
                                <el-table-column
                                        prop="userName"
                                        label="上传用户"
                                        align="center"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        label="来源平台"
                                        align="center"
                                        width="90">
                                    <template slot-scope="scope">
                                        {{scope.row.officialAccount | titleFormatter}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        label="推送状态"
                                        align="center"
                                        width="80">
                                    <template slot-scope="scope">
                                        <label v-if="!scope.row.pushStatus">未推送</label>
                                        <label v-if="scope.row.pushStatus">已推送</label>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="wxView"
                                        label="浏览"
                                        align="center"
                                        sortable
                                        width="75">
                                </el-table-column>
                                <el-table-column
                                        prop="shareNum"
                                        label="分享"
                                        align="center"
                                        sortable
                                        width="75">
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="上传时间"
                                        align="center"
                                        sortable
                                        width="170">
                                </el-table-column>

                                <el-table-column
                                        label="操作"
                                        align="center">
                                    <template slot-scope="scope">
                                        <el-button
                                                size="mini"
                                                type="primary"
                                                @click="handlePush(scope.row._id,1)" v-if="!scope.row.pushStatus">推送
                                        </el-button>
                                        <el-button
                                                size="mini"
                                                type="primary"
                                                @click="handlePush(scope.row._id,0)" v-if="scope.row.pushStatus">取消推送
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <nav style="margin-top: 20px">
                                <el-pagination
                                        layout="total, sizes, prev, pager, next"
                                        :total="total"
                                        :hide-on-single-page="pageActive"
                                        @size-change="handleSizeChange"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        :page-sizes="[10, 20, 30, 40]"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
    import common from '../../api/public.js';
    import CompanyMenuComponents from "./CompanyMenuComponents";
    export default {
        name: "CompanyVideoComponent",
        components: {
            "company-menu-components": CompanyMenuComponents,
        },
        data() {
            return {
                url: '',
                keyword: '',
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: '2',
                name: '',
                order: 'desc',
                orderField: '_id',
                form: {
                    name: "",
                    categoryName: '',
                    editName: "",
                    editIndustryName: '',
                    editAlternativeName: [],
                },
                options: [{
                    value: -1,
                    label: '全部'
                }, {
                    value: 1,
                    label: '显示'
                }, {
                    value: 0,
                    label: '隐藏'
                }],
                search_status: -1,
                formLabelWidth: '120px',
                dialogTableVisible: false,
                //公司部分
                alternativeName: [],
                categoryName: '',
                categoryTags: [],
                categoryIds: [],
                inputVisible: false,
                inputValue: '',
                companyName: '',
                status: 0,
                companyId: $('meta[name="id"]').attr('content'),
            }
        },
        methods: {
            ...common,
            search: function () {
                let self = this;
                let uri = 'article/video/cartoon/post-list';
                self.loading = true;

                let postData = {
                    type:2,
                    keyword: self.keyword,
                    page: self.currentPage,
                    order: self.order,
                    orderField: self.orderField,
                    verifyStatus: 1,
                    companyId: self.companyId
                };

                axios.post(uri, postData).then(function (result) {
                    self.total = result.data.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.data.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleDelete: function (row) {
                let self = this;
                let tipStr = "此操作将永久删除“" + row.name + "”, 是否继续?";
                self.$confirm(tipStr, '产品删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.deleteRequire(row._id)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteRequire: function (id) {
                let self = this;
                let uri = "/admin/goods/" + id;
                self.loading = true;
                axios.delete(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            getInfo() {
                let self = this;
                let uri = "company/" + self.companyId;
                self.loading = true;
                axios.get(uri).then(function (data) {
                    let result = data.result;
                    self.companyName = result.name;
                    self.status = 0;
                    self.status = result.status;

                    self.categoryIds = [];
                    self.categoryTags = [];
                    self.alternativeName = [];

                    self.alternativeName = result.alternativeName;
                    self.categoryTags = result.categoryNames;

                    result.categoryNames.forEach((item) => {
                        self.categoryIds.push(item.id)
                    });
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleSizeChange: function (pageSize) {
                this.pageSize = pageSize;
                this.search();
            },
            sortChange(item) {
                let order = "asc";
                this.orderField = item.prop;
                if (item.order === 'descending') {
                    order = "desc";
                }
                this.order = order;
                this.search();
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            indexMethod: function (index) {
                return index + 1;
            },

            //下面是标签部分
            handleClose(tag) {
                this.alternativeName.splice(this.alternativeName.indexOf(tag), 1);
                this.updateCompany();
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;

                if (inputValue && this.alternativeName.indexOf(inputValue) == -1) {
                    this.alternativeName.push(inputValue);
                    this.updateCompany();
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            //查询分类
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async querySearchAsync(queryString, cb) {
                await this.queryIndustry(queryString);
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleSelect(item) {
                if (item && this.categoryIds.indexOf(item.id) == -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                    this.updateCompany();
                }
                this.categoryName = '';
            },
            handleIndustryClose(tag) {
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.splice(this.categoryIds.indexOf(tag.id), 1);
                this.updateCompany();
            },
            updateCompany() {
                let self = this;
                self.loading = true;
                let uri = "company/update/" + self.companyId;
                let postData = {
                    alternativeName: self.alternativeName,
                    categoryIds: self.categoryIds
                };
                axios.put(uri,postData).then(function (result) {
                    self.loading = false;
                    self.getInfo();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleSetStatus(id, status) {
                let self = this;
                let uri = "company/set-status/" + id + "/" + status;
                axios.get(uri).then(function (result) {
                    self.getInfo();
                });
            },
            handlePush: function (id,pushStatus) {
                let self = this;
                let tipStr = "确定该操作, 是否继续?";
                self.$confirm(tipStr, '推送设置', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.pushRequire(id,pushStatus)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消操作'
                    });
                });
            },pushRequire: function (id,pushStatus) {
                let self = this;
                let uri = "article/video/cartoon/push/" + id + '/' + pushStatus;
                self.loading = true;
                axios.get(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            openEdit(id) {
                this.openUri('video/' + id + '/edit');
            },
            formatCompany: function (row, column) {
                return this.filterLength(row.companyStr, 4);
            },
            filterLength: function (str, length = 9) {
                if (str.length >= length) {
                    return str.substring(0, length) + '...';
                }
                return str.length === 0 ? '--' : str;
            },
            draw() {
                let self = this;
                let uri = "video/draw";
                let videoUrl = this.url;
                if (!videoUrl) {
                    self.$message.error('提取链接不能为空！');
                    return;
                }
                let postData = {url: videoUrl,companyTags:[this.companyId]};
                axios.put(uri,postData).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            }
        },
        mounted() {
            this.queryIndustry();
            this.search();
            this.getInfo();
        },
        filters: {
            titleFormatter(title) {
                title = !title ? '' : title;
                if (title.length >= 10) {
                    return title.substring(0, 10) + '...';
                }
                return title.length === 0 ? '--' : title;
            }
        }
    }
</script>

<style scoped>
    .card-toolbar .form-inline .form-group {
        display: block;
        margin-bottom: 15px;
    }

    .input-group-addon, .input-group-btn {
        width: 100%;
    }
</style>
